package cn.vortex.device.service.impl;

import cn.vortex.device.dao.impl.UserDaoImpl;
import cn.vortex.device.service.UserService;
import cn.vortex.device.tool.JdbcUtil;
import cn.vortex.device.tool.ResMessageBuilder;
import cn.vortex.device.vo.PageVo;
import cn.vortex.device.vo.ResMessage;
import cn.vortex.device.vo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class UserServiceImpl implements UserService {

    //Oracle
    private static final String BASE_FIELD = "id,account,password,username,roleID";

    private UserDaoImpl userDao = new UserDaoImpl();

    private static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Override
    public ResMessage userLogin(HttpServletRequest request,String account, String password) {

        logger.info("user login account ["+account+"],password ["+password+"]");

        String sql = "select * from t_user where account = ?";

        try {
            User user = userDao.findObject(sql,User.class,account);
            if (user != null){
                if (user.getAccount().equals(account) && user.getPassword().equals(password)){
                    request.getSession().setAttribute("USER", user);
                    request.getSession().setAttribute("roleID", user.getRoleId());
                    logger.info("login success user["+user+"]");
                    return ResMessageBuilder.resMessage(200,"success","登录成功");
                } else{
                    logger.info("login fail user["+user+"] 用户名或密码错误");
                    return ResMessageBuilder.resMessage(200,"fail","用户名或密码错误");
                }
            }else {
                logger.info("login fail 未找到该用户");
                return ResMessageBuilder.resMessage(200,"fail","未找到该用户");
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.info("login fail ["+e.getMessage()+"]");
            return ResMessageBuilder.resMessage(200,"fail","系统错误");
        }
    }

    @Override
    public User getObjByAccount(String account) throws Exception {
        return userDao.findByAccount(account);
    }


    @Override
    public List listAll() throws Exception {
        return userDao.findAll();
    }

    @Override
    public User getObjById(Integer id) throws Exception {
        return userDao.findById(id);
    }

    @Override
    public boolean deleteObjById(Integer id) throws Exception {
        return userDao.deleteById(id) > 0;
    }

    @Override
    public boolean updateObj(User user) throws Exception {
        return userDao.update(user) > 0;
    }

    @Override
    public boolean addObj(User user) throws Exception {
        return userDao.insert(user) > 0;
    }

    @Override
    public User getObj(String sql, Object... params) throws Exception {
        return null;
    }


    @Override
    public boolean deleteObj(Object... params) throws Exception {
        return false;
    }

    @Override
    public boolean deleteObjList(Set<Integer> ids) throws Exception {
        if (ids == null || ids.isEmpty()) return false;
        int count = 0;
        for (Integer id : ids) {
            if (deleteObjById(id)) {
                count++;
            }
        }
        return count == ids.size();
    }

    @Override
    public List listObj(String sql, Object... params) throws Exception {
        return null;
    }

    @Override
    public PageVo<User> pageObj(String currentPage, String rows, Map<String, Object> resources) throws Exception {
        List<Object> params = new ArrayList<>();

        StringBuffer queryPage = new StringBuffer();

        //Oracle
        queryPage.append("select " + BASE_FIELD + " from t_user ");

        StringBuffer queryCount = new StringBuffer();

        queryCount.append("select count(1) from t_user");

        PageVo<User> pageVo = null;
        try {
            JdbcUtil.startTransaction();
            if (resources != null && resources.size() != 0){
                queryPage.append(" where ");
                queryCount.append(" where ");
                Set<String> set = resources.keySet();
                set.forEach(key ->{
                    Object value = resources.get(key);
                    if (value != null){
                        //MySQL
                        //queryPage.append(key).append(" like concat('%',?,'%') and ");
                        //queryCount.append(key).append(" like concat('%',?,'%') and ");
                        //Oracle
                        queryPage.append(key).append(" like concat(concat('%',?), '%') and ");
                        queryCount.append(key).append(" like concat(concat('%',?), '%') and ");

                        params.add(value);
                    }
                });
                queryCount.delete(queryCount.lastIndexOf("and "),queryCount.length());
                queryPage.delete(queryPage.lastIndexOf("and"),queryPage.length());
                //MySQL
                //queryPage.append("limit ? ,?");
                //Oracle
                queryPage.append(" and rownum < (?)\n" +
                        "minus\n")
                        .append("select " + BASE_FIELD + " from t_user " +
                                " where rownum < (?)");

                int count = userDao.findCount(queryCount.toString(), params.toArray());

                pageVo = new PageVo<>(currentPage,rows,count);

                System.out.println("queryPage:"+queryPage.toString());
                System.out.println("queryCount:"+queryCount.toString());

                //MySQL
                //params.add(pageVo.getStart());
                //params.add(pageVo.getRows());
                //Oracle
                params.add(pageVo.getRows() + pageVo.getStart());
                params.add(pageVo.getStart());

                List<User> data = userDao.findByPage(queryPage.toString(), User.class, params.toArray());

                pageVo.setData(data);

            }else {
                //MySQL
                //queryPage.append("limit ? ,?");
                //Oracle
                queryPage.append("where rownum < (?)\n" +
                        "minus\n")
                        .append("select " + BASE_FIELD + " from t_user " +
                                "where rownum < (?)");

                int count = userDao.findCount(queryCount.toString(), params.toArray());

                pageVo = new PageVo<>(currentPage,rows,count);

                //MySQL
                //params.add(pageVo.getStart());
                //params.add(pageVo.getRows());
                //Oracle
                params.add(pageVo.getRows() + pageVo.getStart());
                params.add(pageVo.getStart());

                System.out.println("queryPage:"+queryPage.toString());
                System.out.println("queryCount:"+queryCount.toString());

                List<User> data = userDao.findByPage(queryPage.toString(), User.class, params.toArray());

                pageVo.setData(data);

            }
        } catch (Exception e) {
            e.printStackTrace();
            JdbcUtil.rollback();
        } finally {
            JdbcUtil.commit();
        }

        return pageVo;
    }

    @Override
    public PageVo<User> pageObj(String user, String currentPage, String rows, Map<String, Object> resources) throws Exception {
        List<Object> params = new ArrayList<>();

        StringBuffer queryPage = new StringBuffer();

        //Oracle
        queryPage.append("select " + BASE_FIELD + " from t_user ");

        StringBuffer queryCount = new StringBuffer();

        queryCount.append("select count(1) from t_user");

        PageVo<User> pageVo = null;
        try {
            JdbcUtil.startTransaction();
            if (resources != null && resources.size() != 0){
                queryPage.append(" where username = '" + user + "' and ");
                queryCount.append(" where username = '" + user + "' and ");
                Set<String> set = resources.keySet();
                set.forEach(key ->{
                    Object value = resources.get(key);
                    if (value != null){
                        //MySQL
                        //queryPage.append(key).append(" like concat('%',?,'%') and ");
                        //queryCount.append(key).append(" like concat('%',?,'%') and ");
                        //Oracle
                        queryPage.append(key).append(" like concat(concat('%',?), '%') and ");
                        queryCount.append(key).append(" like concat(concat('%',?), '%') and ");

                        params.add(value);
                    }
                });
                queryCount.delete(queryCount.lastIndexOf("and "),queryCount.length());
                queryPage.delete(queryPage.lastIndexOf("and"),queryPage.length());
                //MySQL
                //queryPage.append("limit ? ,?");
                //Oracle
                queryPage.append(" and rownum < (?)\n" +
                        "minus\n")
                        .append("select " + BASE_FIELD + " from t_user" +
                                " where username = '" + user +
                                "' and rownum < (?)");

                int count = userDao.findCount(queryCount.toString(), params.toArray());

                pageVo = new PageVo<>(currentPage,rows,count);

                System.out.println("queryPage:"+queryPage.toString());
                System.out.println("queryCount:"+queryCount.toString());

                //MySQL
                //params.add(pageVo.getStart());
                //params.add(pageVo.getRows());
                //Oracle
                params.add(pageVo.getRows() + pageVo.getStart());
                params.add(pageVo.getStart());

                List<User> data = userDao.findByPage(queryPage.toString(), User.class, params.toArray());

                pageVo.setData(data);

            }else {
                //MySQL
                //queryPage.append("limit ? ,?");
                //Oracle
                queryPage.append("where username = '" + user + "' and rownum < (?)\n" +
                        "minus\n")
                        .append("select " + BASE_FIELD + " from t_user" +
                                " where username = '" + user +
                                "' and rownum < (?)");

                int count = userDao.findCount(queryCount.toString(), params.toArray());

                pageVo = new PageVo<>(currentPage,rows,count);

                //MySQL
                //params.add(pageVo.getStart());
                //params.add(pageVo.getRows());
                //Oracle
                params.add(pageVo.getRows() + pageVo.getStart());
                params.add(pageVo.getStart());

                System.out.println("queryPage:"+queryPage.toString());
                System.out.println("queryCount:"+queryCount.toString());

                List<User> data = userDao.findByPage(queryPage.toString(), User.class, params.toArray());

                pageVo.setData(data);

            }
        } catch (Exception e) {
            e.printStackTrace();
            JdbcUtil.rollback();
        } finally {
            JdbcUtil.commit();
        }

        return pageVo;
    }
}
